﻿using UnityEngine;
using System.Collections;

public class ValueReacher : Actor
{
	private float 	m_CurrentValue;
	public float 	CurrentValue
	{
		get { return m_CurrentValue; }
	}

	private float 	m_Start;
	private float 	m_End;
	private float	m_Duration;
	private bool	m_BackAndForth;
	private bool	m_AutoDestruct;

	private float 	m_CurrentLerpValue;
	private bool	m_Begin = false;
	private bool 	m_ReachedOnce = false;

	public delegate void Callback();
	public Callback m_OnValueReached;
	public Callback m_OnFinish;

	public void SetupValues(float i_Start, float i_End, float i_Duration, bool i_BackAndForth = true, bool i_AutoDestruct = true)
	{
		m_Begin = 			true;
		m_ReachedOnce = 	false;

		m_CurrentValue =	i_Start;
		m_Start = 			i_Start;
		m_End = 			i_End;
		m_Duration = 		i_Duration;
		m_BackAndForth = 	i_BackAndForth;
		m_AutoDestruct = 	i_AutoDestruct;
	}

	public void Reset()
	{
		m_Begin = 				false;
		m_ReachedOnce = 		false;
					 	
		m_Start = 				0;
		m_End = 				0;
		m_Duration = 			0;
		m_CurrentValue = 		0;
		m_CurrentLerpValue = 	0;
		m_BackAndForth = 		true;
		m_AutoDestruct = 		true;
	}

	private void Update () 
	{
		if(m_Begin)
		{
			m_CurrentLerpValue += Time.deltaTime/m_Duration;

			if(m_CurrentLerpValue > 1f)
			{
				m_CurrentLerpValue = 1f;
			}

			m_CurrentValue = Mathf.Lerp(m_Start, m_End, m_CurrentLerpValue);

			if(m_CurrentLerpValue == 1f)
			{
				if(m_OnValueReached != null) m_OnValueReached();

				if(m_ReachedOnce)
				{
					if(m_OnFinish != null) m_OnFinish();

					if(m_AutoDestruct)
					{
						Destroy (this);
					}
					else
					{
						Reset ();
					}
				}
				else
				{
					if(m_BackAndForth)
					{
						m_CurrentLerpValue = 0f;
						float start = m_Start;
						m_Start = m_End;
						m_End = start;
					}
					else
					{
						if(m_OnFinish != null) m_OnFinish();
						
						if(m_AutoDestruct)
						{
							Destroy (this);
						}
						else
						{
							Reset ();
						}
					}
				}

				m_ReachedOnce = true;
			}
		}
	}
}
